package ru.hh.school;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

import static ru.hh.school.Util.readPortFromAppArgs;
import static ru.hh.school.Util.usage;

public class ClientInputConsole {
    public static void main(String[] args) {

        final int port = readPortFromAppArgs(args);
        if (port == -1) return;

        BufferedReader consoleIn = new BufferedReader(new InputStreamReader(System.in));
        Socket socket = null;
        int attemptsToConnect = 0;
        final int maxAttemptsToConnect = 5;
        final int delay = 50;
        while ((attemptsToConnect < maxAttemptsToConnect) && (socket == null)) {
            try {
                Thread.sleep(delay);
            } catch (InterruptedException ignored) {
            }
            try {
                final String loopbackAddress = null;
                socket = new Socket(loopbackAddress, port);
            } catch (UnknownHostException e) {
                usage();
                return;
            } catch (IOException e) {

            }
            attemptsToConnect++;
        }
        if (socket == null) {
            System.err.println("Cannot connect to ClientChatConsole application");
            return;
        }
        ObjectOutputStream localEndpointOut = null;
        System.out.println("Type commands and messages here");
        try {
            localEndpointOut = new ObjectOutputStream(socket.getOutputStream());
            while (true) {
                String input = consoleIn.readLine();
                if (!input.startsWith("/")) {
                    input = "/send " + input;
                }
                localEndpointOut.writeObject(input);
            }
        } catch (Exception e) {
            // I'm afraid of stacktraces!
            // e.printStackTrace();
        } finally {
            if (localEndpointOut != null) {
                try {
                    localEndpointOut.close();
                } catch (IOException e1) {
                    // I'm afraid of stacktraces!
                    // e1.printStackTrace();
                }
            }

        }
    }
}
